package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.feign.article.IArticleClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.mapper.WmchannelMapper;
import com.heima.wemedia.service.GreenScanService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author rookie001
 * @creat 2023-06-11-11:36
 */
@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenScanService greenScanService;
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private WmchannelMapper wmchannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private Tess4jClient tess4jClient;
    @Autowired
    private RedisTemplate redisTemplate;

    /*
        文章自动审核                 自媒体文章id*/
    @Override
//    @Async
    public void autoScanWmNews(Integer id) {
        //根据id 获取wmnews实体
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断是否为待审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //从内容中提取纯文本内容和图片
            Map<String, Object> conAndPic = ExtractContentPicture(wmNews);
            //文本敏感词匹配
            boolean a = scanSensitive((String) conAndPic.get("text"), wmNews);
            if (!a) return;
            //审核文章文本
            Boolean c = scanText((String) conAndPic.get("text"), wmNews);
            if (!c) return;
            //审核文章 图片
            boolean d = scanImages((List<String>) conAndPic.get("images"), wmNews);
            if (!d) return;
            //审核通过 保存或修改到app端 -远程调用saveArticle()方法
            ResponseResult responseResult = saveAppAticle(wmNews);
            //审核通过  回填article_id到wmnews中
            if (responseResult.getCode().equals(200)) {
                wmNews.setArticleId((Long) responseResult.getData());
                updateWmuser(wmNews, (short) 9, "审核成功");
            }
        }
    }


    /*    审核通过
    保存或修改到app端*/
    private ResponseResult saveAppAticle(WmNews wmNews) {
        //创建articleDTO 将wmnews数据拷贝到articleDTO
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        //设置其他字段
        //文章布局
        if (wmNews.getType() != null) {
            dto.setLayout(wmNews.getType());
        }
        //频道
        if (wmNews.getChannelId() != null) {
            WmChannel wmChannel = wmchannelMapper.selectById(wmNews.getChannelId());
            dto.setChannelName(wmChannel.getName());
        }
        //作者  和id
        long userId = wmNews.getUserId();
        dto.setAuthorId(userId);
        WmUser wmUser = wmUserMapper.selectById(userId);
        if (wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }
        //远程调用 返回数据
        return iArticleClient.saveArticle(dto);

    }



    //文本敏感词审核
    private boolean scanSensitive(String text, WmNews wmNews) {
        if (text!=null) {
            //wm_sensitive中获取敏感词

            List<String> sensitive = (List<String>) redisTemplate.opsForValue().get("Sensitive");
            if (sensitive == null) {
                //提取敏感词
                List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
                //转换成collection
                sensitive = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
                //放入缓存
                redisTemplate.opsForValue().set("Sensitive", sensitive);
            }
            //初始化敏感词库
            SensitiveWordUtil.initMap(sensitive);
            //调用工具类判断是否包含敏感词
            Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
            if (map.size() > 0) {
                //包含则更新wm_news
                updateWmuser(wmNews, (short) 2, "包含敏感词");

                log.info("敏感词审核失败 {}",map);

                return false;
            }
        }
        return true;
    }



    //审核图片 及图文
    private boolean scanImages(List<String> images, WmNews wmNews) {
        boolean flag = true;
        for (String image : images) {
            Map map = greenScanService.scanImage(image);
             log.info("图片审核详情为:{}",map);

            //图片审核文字
            byte[] bytes = fileStorageService.downLoadFile(image);
            try {
                //从byte[]转换为bufferedImage
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage imageFile = ImageIO.read(in);
                //识别图片的文字
                String result = tess4jClient.doOCR(imageFile);

                //审核是否包含自管理的敏感词
                boolean isSensitive = scanSensitive(result, wmNews);
                if(!isSensitive){
                    return isSensitive;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            //审核图片
            //如果 conclusionType =2 则审核失败
            if (map != null) {
                if (map.get("conclusionType").equals("2")) {
                    flag = false;
                    updateWmuser(wmNews, (short) 3, "图片违规");
                } else if (map.get("conclusionType").equals("3")) {
                    //如果 conclusionType =3 则人工审核
                    flag = false;
                    updateWmuser(wmNews, (short) 2, "图片疑似违规");
                }
                return flag;
            }
        }
        return flag;
    }



    //审核文本
    private Boolean scanText(String text, WmNews wmNews) {
        boolean flag = true;
        //调用百度API
        Map map = greenScanService.scanText(text);
        //如果 conclusionType =2 则审核失败
        if (map != null) {
            if (map.get("conclusionType").equals("2")) {
                flag = false;
                updateWmuser(wmNews, (short) 2, "文本违规");
            } else if (map.get("conclusionType").equals("3")) {
                //如果 conclusionType =3 则人工审核
                flag = false;
                updateWmuser(wmNews, (short) 2, "文本疑似违规");
            }
            //成功返回true
            return flag;
        }
        return flag;
    }



    //从内容中提取纯文本内容和图片 封面图片
    private Map<String, Object> ExtractContentPicture(WmNews wmNews) {
        //将纯文本放入stringbuilder中
        StringBuilder stringBuilder = new StringBuilder();
        //审核标题 标签
        stringBuilder.append(wmNews.getTitle());
        stringBuilder.append(wmNews.getLabels());
        //将图片放入list中
        List<String> images = new ArrayList<>();
        //提取文本内容 和图片
        if (wmNews.getContent() != null) {
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("text")) {
                    stringBuilder.append(map.get("value"));
                }
                if (map.get("type").equals("image")) {
                    images.add((String) map.get("value"));
                }
            }
        }
        //提取 封面图片
        if (wmNews.getImages() != null) {
            String[] split = wmNews.getImages().split(",");
            //添加到list中
            images.addAll(Arrays.asList(split));
        }
        //返回结果
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("text", stringBuilder.toString());///!!!!!!!!!!!!!转string
        map.put("images", images);
        return map;
    }



    //更新方法抽取
    private void updateWmuser(WmNews wmNews, short i, String text) {
        wmNews.setStatus(i);
        wmNews.setReason(text);
        wmNewsMapper.updateById(wmNews);
    }
}
